﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using School.Entities;

namespace EF.WebApi.Controllers;

/// <summary>
/// 教师管理
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class TeachersController : ControllerBase {
    private readonly SchoolContext _context;

    public TeachersController (SchoolContext context) {
        _context = context;
    }

    ///// <summary>
    ///// 获取教师列表
    ///// </summary>
    ///// <returns></returns>
    //[HttpGet]
    //public async Task<ActionResult<IEnumerable<Teacher>>> GetTeacher () {
    //    return await _context.Teacher
    //        .Include(x=>x.Courses)
    //        .ToListAsync();
    //}

    /// <summary>
    /// 查看某个教师信息
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ActionResult<Teacher>> GetTeacher (int id) {
        var teacher = await _context.Teacher.FindAsync(id);

        if (teacher == null) {
            return NotFound();
        }

        return teacher;
    }

    /// <summary>
    /// 修改某个教师信息
    /// </summary>
    /// <param name="id"></param>
    /// <param name="teacher"></param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task<IActionResult> PutTeacher (int id, Teacher teacher) {
        if (id != teacher.Id) {
            return BadRequest();
        }

        _context.Entry(teacher).State = EntityState.Modified;

        try {
            await _context.SaveChangesAsync();
        } catch (DbUpdateConcurrencyException) {
            if (!TeacherExists(id)) {
                return NotFound();
            } else {
                throw;
            }
        }

        return NoContent();
    }

    /// <summary>
    /// 添加一条教师信息
    /// </summary>
    /// <param name="teacher"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ActionResult<Teacher>> PostTeacher (Teacher teacher) {
        _context.Teacher.Add(teacher);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetTeacher", new { id = teacher.Id }, teacher);
    }

    /// <summary>
    /// 删除某条教师信息
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteTeacher (int id) {
        var teacher = await _context.Teacher.FindAsync(id);
        if (teacher == null) {
            return NotFound();
        }

        _context.Teacher.Remove(teacher);
        await _context.SaveChangesAsync();

        return NoContent();
    }

    /// <summary>
    /// 某教师是否存在
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private bool TeacherExists (int id=1) {
        return _context.Teacher.Any(e => e.Id == id);
    }
}
